<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import { message } from 'ant-design-vue'

const props = defineProps({
    component: {
        type: Object,
        required: true
    },
    selected: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(['click', 'move', 'resize'])

const componentRef = ref()
const isDragging = ref(false)
const isResizing = ref(false)
const dragStart = ref({ x: 0, y: 0 })
const resizeStart = ref({ x: 0, y: 0, width: 0, height: 0 })
const hasDragged = ref(false) // 追踪是否发生了拖动

// 计算样式
const computedStyle = computed(() => ({
    ...props.component.style,
    cursor: isDragging.value ? 'grabbing' : 'grab'
}))

// 处理API调用
const callApi = async (apiConfig) => {
    if (!apiConfig || !apiConfig.url) return

    try {
        const response = await axios({
            method: apiConfig.method,
            url: apiConfig.url,
            headers: apiConfig.headers,
            data: apiConfig.body
        })

        message.success('API调用成功')
        console.log('API Response:', response.data)
    } catch (error) {
        message.error('API调用失败: ' + error.message)
        console.error('API Error:', error)
    }
}

// 处理事件
const handleClick = (event) => {
    // 如果刚刚发生了拖动，不触发点击事件
    if (hasDragged.value) {
        hasDragged.value = false
        return
    }
}

const handleChange = (value) => {
    // 执行onChange事件
    if (props.component.events?.onChange) {
        callApi(props.component.events.onChange)
    }
}

const handleInput = (value) => {
    // 执行onInput事件
    if (props.component.events?.onInput) {
        callApi(props.component.events.onInput)
    }
}

// 拖拽功能
const handleMouseDown = (event) => {
    // 如果组件未被选中，先触发选中事件
    if (!props.selected) {
        // 通过 emit click 事件来选中组件
        const isCtrlPressed = event.ctrlKey || event.metaKey
        emit('click', event)
    }
    
    // 允许在任何时候开始拖动
    isDragging.value = true
    hasDragged.value = false // 重置拖动标记
    dragStart.value = {
        x: event.clientX - (props.component.position?.x || 0),
        y: event.clientY - (props.component.position?.y || 0)
    }

    event.preventDefault()
    event.stopPropagation() // 阻止事件冒泡到画布
}

const handleMouseMove = (event) => {
    if (!isDragging.value) return

    hasDragged.value = true // 标记已经发生了拖动
    
    const newPosition = {
        x: Math.max(0, event.clientX - dragStart.value.x),
        y: Math.max(0, event.clientY - dragStart.value.y)
    }

    emit('move', newPosition)
}

const handleMouseUp = () => {
    isDragging.value = false
    isResizing.value = false
}

// 大小调整功能
const handleResizeStart = (event) => {
    if (!props.selected) return

    isResizing.value = true
    resizeStart.value = {
        x: event.clientX,
        y: event.clientY,
        width: props.component.size?.width || 100,
        height: props.component.size?.height || 32
    }

    event.stopPropagation()
    event.preventDefault()
}

const handleResizeMove = (event) => {
    if (!isResizing.value) return

    const deltaX = event.clientX - resizeStart.value.x
    const deltaY = event.clientY - resizeStart.value.y

    const newSize = {
        width: Math.max(20, resizeStart.value.width + deltaX),
        height: Math.max(20, resizeStart.value.height + deltaY)
    }

    emit('resize', newSize)
}

onMounted(() => {
    document.addEventListener('mousemove', handleMouseMove)
    document.addEventListener('mouseup', handleMouseUp)
    document.addEventListener('mousemove', handleResizeMove)
})

// 组合组件渲染辅助方法
const getChildComponent = (child) => {
    const componentMap = {
        'button': 'a-button',
        'link': 'a',
        'icon': 'span',
        'text': 'div',
        'label': 'span',
        'image': 'img',
        'input': 'a-input',
        'textarea': 'a-textarea',
        'password': 'a-input-password',
        'number-input': 'a-input-number',
        'search': 'a-input-search',
        'select': 'a-select',
        'radio-group': 'a-radio-group',
        'checkbox-group': 'a-checkbox-group',
        'switch': 'a-switch',
        'slider': 'a-slider',
        'rate': 'a-rate',
        'date-picker': 'a-date-picker',
        'time-picker': 'a-time-picker',
        'tag': 'a-tag',
        'badge': 'a-badge',
        'progress': 'a-progress',
        'alert': 'a-alert'
    }
    return componentMap[child.type] || 'div'
}

const getChildProps = (child) => {
    const baseProps = { ...child.props }

    // 添加通用样式
    const style = { width: '100%', height: '100%' }

    switch (child.type) {
        case 'link':
            return {
                href: baseProps.href,
                target: baseProps.target,
                style: { ...style, color: baseProps.color }
            }
        case 'icon':
            return {
                style: {
                    ...style,
                    fontSize: baseProps.size,
                    color: baseProps.color
                }
            }
        case 'text':
            return {
                style: {
                    ...style,
                    fontSize: baseProps.fontSize,
                    color: baseProps.color,
                    fontWeight: baseProps.fontWeight,
                    textAlign: baseProps.textAlign,
                    lineHeight: '1.5',
                    whiteSpace: 'pre-wrap'
                }
            }
        case 'label':
            return {
                style: {
                    ...style,
                    color: baseProps.color,
                    fontSize: baseProps.fontSize
                }
            }
        case 'image':
            return {
                src: baseProps.src,
                alt: baseProps.alt,
                style: {
                    ...style,
                    objectFit: baseProps.fit
                }
            }
        case 'button':
            return {
                type: baseProps.type,
                size: baseProps.size,
                disabled: baseProps.disabled,
                style: { ...style, minHeight: 'auto' }
            }
        default:
            return { ...baseProps, style }
    }
}

onUnmounted(() => {
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
    document.removeEventListener('mousemove', handleResizeMove)
})
</script>

<template>
    <div ref="componentRef" :style="computedStyle" :class="{
        'component-selected': selected,
        'component-hover': !selected
    }" class="component-wrapper" @click="handleClick" @mousedown="handleMouseDown">
        <!-- 按钮组件 -->
        <a-button v-if="component.type === 'button'" :type="component.props.type" :size="component.props.size"
            :disabled="component.props.disabled" :style="{ width: '100%', height: '100%', minHeight: 'auto' }">
            {{ component.props.text }}
        </a-button>

        <!-- 链接组件 -->
        <a v-else-if="component.type === 'link'" :href="component.props.href" :target="component.props.target"
            :style="{ color: component.props.color }">
            {{ component.props.text }}
        </a>

        <!-- 图标组件 -->
        <span v-else-if="component.type === 'icon'" :style="{
            fontSize: component.props.size,
            color: component.props.color
        }">
            ⭐
        </span>

        <!-- 文本组件 -->
        <div v-else-if="component.type === 'text'" :style="{
            fontSize: component.props.fontSize,
            color: component.props.color,
            fontWeight: component.props.fontWeight,
            textAlign: component.props.textAlign,
            lineHeight: '1.5',
            whiteSpace: 'pre-wrap'
        }">
            {{ component.props.content }}
        </div>

        <!-- 标签组件 -->
        <span v-else-if="component.type === 'label'" :style="{
            color: component.props.color,
            fontSize: component.props.fontSize
        }">
            {{ component.props.text }}
        </span>

        <!-- 图片组件 -->
        <img v-else-if="component.type === 'image'" :src="component.props.src" :alt="component.props.alt"
            :style="{ objectFit: component.props.fit }" class="w-full h-full" />

        <!-- 输入框组件 -->
        <a-input v-else-if="component.type === 'input'" :placeholder="component.props.placeholder"
            :value="component.props.value" :disabled="component.props.disabled" :maxlength="component.props.maxLength"
            :style="{ width: '100%', height: '100%' }" @change="handleChange" @input="handleInput" />

        <!-- 多行文本框组件 -->
        <a-textarea v-else-if="component.type === 'textarea'" :placeholder="component.props.placeholder"
            :value="component.props.value" :disabled="component.props.disabled" :maxlength="component.props.maxLength"
            :rows="component.props.rows" :style="{ width: '100%', height: '100%' }" @change="handleChange"
            @input="handleInput" />

        <!-- 密码输入框组件 -->
        <a-input-password v-else-if="component.type === 'password'" :placeholder="component.props.placeholder"
            :value="component.props.value" :disabled="component.props.disabled"
            :visibility-toggle="component.props.showPassword" :style="{ width: '100%', height: '100%' }"
            @change="handleChange" @input="handleInput" />

        <!-- 搜索输入框组件 -->
        <a-input-search v-else-if="component.type === 'search'" :placeholder="component.props.placeholder"
            :value="component.props.value" :disabled="component.props.disabled"
            :allow-clear="component.props.allowClear" :enter-button="component.props.enterButton"
            :style="{ width: '100%', height: '100%' }" @change="handleChange" @search="handleChange" />

        <!-- 数字输入框组件 -->
        <a-input-number v-else-if="component.type === 'number-input'" :value="component.props.value"
            :min="component.props.min" :max="component.props.max" :step="component.props.step"
            :placeholder="component.props.placeholder" :style="{ width: '100%', height: '100%' }"
            @change="handleChange" />

        <!-- 下拉选择组件 -->
        <a-select v-else-if="component.type === 'select'" :value="component.props.value"
            :placeholder="component.props.placeholder" :disabled="component.props.disabled"
            :options="component.props.options" :style="{ width: '100%', height: '100%' }" @change="handleChange" />

        <!-- 单选框组组件 -->
        <a-radio-group v-else-if="component.type === 'radio-group'" :value="component.props.value"
            :direction="component.props.direction" @change="handleChange">
            <a-radio v-for="option in component.props.options" :key="option.value" :value="option.value">
                {{ option.label }}
            </a-radio>
        </a-radio-group>

        <!-- 多选框组组件 -->
        <a-checkbox-group v-else-if="component.type === 'checkbox-group'" :value="component.props.value"
            :direction="component.props.direction" @change="handleChange">
            <a-checkbox v-for="option in component.props.options" :key="option.value" :value="option.value">
                {{ option.label }}
            </a-checkbox>
        </a-checkbox-group>

        <!-- 开关组件 -->
        <a-switch v-else-if="component.type === 'switch'" :checked="component.props.checked"
            :disabled="component.props.disabled" :size="component.props.size"
            :checked-children="component.props.checkedChildren" :un-checked-children="component.props.unCheckedChildren"
            @change="handleChange" />

        <!-- 滑块组件 -->
        <a-slider v-else-if="component.type === 'slider'" :value="component.props.value" :min="component.props.min"
            :max="component.props.max" :step="component.props.step" :disabled="component.props.disabled"
            :range="component.props.range" :style="{ width: '100%' }" @change="handleChange" />

        <!-- 评分组件 -->
        <a-rate v-else-if="component.type === 'rate'" :value="component.props.value" :count="component.props.count"
            :allow-half="component.props.allowHalf" :disabled="component.props.disabled"
            :allow-clear="component.props.allowClear" @change="handleChange" />

        <!-- 日期选择器组件 -->
        <a-date-picker v-else-if="component.type === 'date-picker'" :value="component.props.value"
            :placeholder="component.props.placeholder" :format="component.props.format"
            :disabled="component.props.disabled" :allow-clear="component.props.allowClear"
            :style="{ width: '100%', height: '100%' }" @change="handleChange" />

        <!-- 时间选择器组件 -->
        <a-time-picker v-else-if="component.type === 'time-picker'" :value="component.props.value"
            :placeholder="component.props.placeholder" :format="component.props.format"
            :disabled="component.props.disabled" :allow-clear="component.props.allowClear"
            :style="{ width: '100%', height: '100%' }" @change="handleChange" />

        <!-- 标签组件 -->
        <a-tag v-else-if="component.type === 'tag'" :color="component.props.color" :closable="component.props.closable">
            {{ component.props.text }}
        </a-tag>

        <!-- 徽标组件 -->
        <a-badge v-else-if="component.type === 'badge'" :count="component.props.count"
            :show-zero="component.props.showZero" :dot="component.props.dot">
            {{ component.props.text }}
        </a-badge>

        <!-- 进度条组件 -->
        <a-progress v-else-if="component.type === 'progress'" :percent="component.props.percent"
            :type="component.props.type" :size="component.props.size" :show-info="component.props.showInfo"
            :status="component.props.status" />

        <!-- 警告提示组件 -->
        <a-alert v-else-if="component.type === 'alert'" :message="component.props.message" :type="component.props.type"
            :show-icon="component.props.showIcon" :closable="component.props.closable"
            :description="component.props.description" />

        <!-- 组合组件 -->
        <div v-else-if="component.type === 'group'" class="w-full h-full relative">
            <!-- 组合组件背景 -->
            <div class="absolute inset-0 pointer-events-none"></div>

            <!-- 渲染子组件 -->
            <div v-for="child in component.children" :key="child.id" class="absolute" :style="{
                left: (child.originalPosition?.x || 0) + 'px',
                top: (child.originalPosition?.y || 0) + 'px',
                width: (child.size?.width || 100) + 'px',
                height: (child.size?.height || 32) + 'px'
            }">
                <!-- 递归渲染子组件内容 -->
                <component :is="getChildComponent(child)" v-bind="getChildProps(child)" />
            </div>

            <!-- 组合名称显示 -->
            <div v-if="selected" class="absolute -top-6 left-0 bg-blue-500 text-white px-2 py-1 text-xs rounded">
                {{ component.props.name || '组合' }}
            </div>
        </div>

        <!-- 未知组件类型 -->
        <div v-else
            class="w-full h-full bg-red-100 border border-red-300 flex items-center justify-center text-red-600 text-sm">
            未知组件: {{ component.type }}
        </div>

        <!-- 选中状态的调整手柄 -->
        <div v-if="selected" class="resize-handle absolute bottom-0 right-0 w-3 h-3 bg-blue-500 cursor-se-resize"
            @mousedown="handleResizeStart"></div>
    </div>
</template>

<style scoped>
.component-wrapper {
    transition: all 0.2s ease;
    user-select: none;
}

.component-wrapper:hover:not(.component-selected) {
    outline: 1px solid #d1d5db;
}

.component-selected {
    outline: 2px solid #3b82f6 !important;
    outline-offset: 1px;
}

.resize-handle {
    transform: translate(50%, 50%);
}

.resize-handle:hover {
    background-color: #2563eb;
}
</style>
